﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Web;
using Facebook;
using System.Windows.Controls;
using System.Collections;
using System.Windows;

namespace Rsa
{
    partial class GestorFacebook
    {
        private GestorConfigXML Gxml = null;
        private List<Lista> _listaFacebook = new List<Lista>();
        private WebBrowser webBrowser;
        private Uri loginUrl;
        private FacebookOAuthResult faceresult;
        private string _loginurl = null;
        private string _acesstoken = null;
        private string _uri = null;
        private string _appid = null;


        public WebBrowser WebBrowser
        {
            get { return webBrowser; }
            set { webBrowser = value; }
        }

        public bool loadConfigFacebook() {

            Hashtable hash = Gxml.loadFacebook();

            Console.WriteLine("LoadConfig Test ");

            LoginUrl = (string)hash["loginurl"];
            if (string.IsNullOrEmpty(LoginUrl.Trim()))
                LoginUrl = null;

            AcessToken = (string)hash["acesstoken"];
            if (string.IsNullOrEmpty(AcessToken.Trim()))
                AcessToken = null;

            UriUrl = (string)hash["uri"];
            if (string.IsNullOrEmpty(UriUrl.Trim()))
                UriUrl = null;

            AppId = (string)hash["appid"];
            if (string.IsNullOrEmpty(AppId.Trim()))
                AppId = null;

            if (AcessToken != null) {
                return true;
            }
            return false;
        }
       

        public GestorFacebook(GestorConfigXML gx)
        {
            Gxml = gx;
            this.loadConfigFacebook();
        }


        public void start(int opcao)
        {

            try
            {

                var appId = AppId;

                string[] extendedPermissions = new[] { "user_about_me", "publish_stream", "offline_access", "read_stream", "read_stream", "offline_access" };


                var fbLoginDialog = auth(appId, extendedPermissions);



                if (fbLoginDialog != null)
                {
                    MessageBox.Show("Registo Concluido");
                }
                else
                {
                    MessageBox.Show("Erro No Registo");

                }


                if (opcao == 0)
                {
                    //opcao 1

                }
                else if (opcao == 1)
                {
                    //opcao 2

                }
                else if (opcao == 2)
                {
                    //opcao 3
                }
            }
            catch (Exception e) {
                Console.WriteLine("Erro" + e);
            }
           
        }

        public FacebookOAuthResult auth(string appId, string[] extendedPermissions)
        {

            var oauth = new FacebookOAuthClient { ClientId = appId };

            var parameters = new Dictionary<string, object>
                    {
                        { "response_type", "token" },
                        { "display", "popup" }
                    };

            if (extendedPermissions != null && extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                parameters["scope"] = scope.ToString();
            }

            this.loginUrl = oauth.GetLoginUrl(parameters);

            JanelaWeb web = new JanelaWeb();

            string uri = web.start(this.loginUrl);

            FacebookOAuthResult result;
            if (FacebookOAuthResult.TryParse(uri, out result))
            {
                this.FacebookOAuthResult = result;
                //this.DialogResult = result.IsSuccess ? DialogResult : DialogResult;
                faceresult = result;
                try
                {
                    Gxml.guardaFacebook(result.AccessToken.ToString());
                }
                catch (Exception e)
                {
                    MessageBox.Show("Tem que validar a Aplicao");
                }
                return result;
            }
            else
            {
                this.FacebookOAuthResult = null;
                faceresult = null;
                return null;
            }
        }

        public bool Dados(int opcao) {

            this.loadConfigFacebook();
            ListaFacebook = new List<Lista>();

            if (loadConfigFacebook() != false)
            {

                var fb = new FacebookClient(AcessToken);

                try
                {
                    dynamic resulted = fb.Get("/me/?fields=feed.fields(message,created_time,from,picture)");
                    //dynamic resulted = fb.Get("/me");
                    var name = resulted.name;

                    Console.WriteLine("HI" + name);

                    foreach (var n in resulted.feed.data)
                    {

                        Lista tmp = new Lista();
                        Console.WriteLine("" + n.from.name);
                        Console.WriteLine("" + n.message);
                        Console.WriteLine("" + n.picture);
                        

                        tmp.Titulo = n.from.name;
                        tmp.Data = n.created_time;

                        tmp.Corpo = "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'> \n";
                     
                        tmp.Corpo += n.picture;
                        tmp.Corpo += n.message;

                        tmp.Imagem = "../../imagens/facebook.png";

                        ListaFacebook.Add(tmp);
                    }
                 
                }
                catch (Exception e)
                {
                    MessageBox.Show("Registe o Facebook" +e);
                    Console.WriteLine("ERRO");
                }
                return true;
             

            }
            else
            {
                Console.WriteLine("NAO TENHO DADOS");
                
            }

            return false;
        
        }

        public bool Post(string message) {

               var fb = new FacebookClient(AcessToken);

               try
               {

                   var postparameters = new Dictionary<string, object>();
                   postparameters["message"] = message;

                   var result = fb.Post("/me/feed", postparameters);
                   return true;

               }
               catch (Exception e)
               {
                   MessageBox.Show("POST FALHOU" + e.Message.ToString());
                   return false;
               }
            
        }



        public List<Lista> ListaFacebook
        {
            get { return _listaFacebook; }
            set { _listaFacebook = value; }
        }
        public FacebookOAuthResult FacebookOAuthResult { get; private set; }

        #region set and gets

        public string LoginUrl {
            get { return _loginurl ;}
            set { _loginurl = value;}
        }

        public string AcessToken {
            get { return _acesstoken;}
            set { _acesstoken = value;} 
        }

        public string UriUrl {
            get { return _uri;}
            set { _uri = value;}
        }

        public string AppId { get { return _appid;} set{_appid = value;} }
        #endregion


    }
}
